package com.xgpro.pc.studycentre.service.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiFileUploadSingleRequest;
import com.dingtalk.api.response.OapiFileUploadSingleResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.taobao.api.FileItem;
import com.taobao.api.internal.util.WebUtils;
import com.xgpro.common.dingtalk.auth.AuthHelper;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.results.ResponseResult;
import com.xgpro.common.service.BaseService;
import com.xgpro.common.utils.FileTool;
import com.xgpro.common.utils.ReadPropertiesUtil;
import com.xgpro.domain.studycentre.entity.Plan;
import com.xgpro.domain.studycentre.vo.PlanFront;
import com.xgpro.domain.studycentre.vo.PlanPCFront;
import com.xgpro.domain.studycentre.vo.PlanPCResult;
import com.xgpro.mapper.studycentre.PlanMapper;
import com.xgpro.pc.studycentre.service.PlanPCService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;


import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;


/**
 * @author tx
 * @version 1.0
 * @date 2019/10/15 20:33
 */
@Service
@Transactional(readOnly = false)
public class PlanPCServiceImpl extends BaseService implements PlanPCService {

    /**
     * 未删除状态
     */
    private static final Integer NOREF=0;

    /**
     * 删除状态
     */
    private static final Integer REF=1;

    @Resource
    private PlanMapper planMapper;

    @Value("${DD_ENV.APP_KEY}")
    private String APP_KEY;
    @Value("${DD_ENV.CORP_ID}")
    private String CORP_ID;

    @Value("${DD_ENV.APP_SECRET}")
    private String APP_SECRET;

    @Value("${DD_ENV.AGENTID}")
    private String AGENTID;




    /**
     * 培训列表
     * @param planPCFront
     * @return
     */
    @Override
    public PlanPCResult qryPlanPCResult(PlanPCFront planPCFront) {
        Example example = new Example(Plan.class);
        Example.Criteria criteria = example.createCriteria();
        if(planPCFront.getPlanName()!=null&&!"".equals(planPCFront.getPlanName())){
            criteria.andLike("planName","%"+planPCFront.getPlanName()+"%");
        }
        criteria.andEqualTo("planYear",planPCFront.getPlanYear());
        criteria.andEqualTo("ref",NOREF);
        PageHelper.startPage(planPCFront.getPage(),planPCFront.getPageSize());
        Page<Plan> pages= (Page<Plan>)planMapper.selectByExample(example);
        PlanPCResult planPCResult = new PlanPCResult();

        List<Plan> result = pages.getResult();
        if (null != result) {
            for (Plan plan : result) {
                String filePath = plan.getFilePath().replace(ReadPropertiesUtil.readUrl("nginxUrl"), ReadPropertiesUtil.readUrl("upload_path"));
//                String filePath = plan.getFilePath();
                File file = new File(filePath);
                String name = file.getName();
                plan.setFileName(name);
                long length = file.length();
                plan.setFileLen(length + "");
                plan.setFilePath(filePath);
                plan.setAgentId(AGENTID);
                plan.setAppKey(APP_KEY);
                plan.setAppSecret(APP_SECRET);
                plan.setCorpId(CORP_ID);
            }
        }
        if(pages!=null){
            planPCResult.setTotals(pages.getTotal());
            planPCResult.setPlans(pages.getResult());
        }
        return planPCResult;
    }

    /**
     * 通过id删除培训计划
     * @param id
     * @return
     */
    @Override
    public Integer deleteByPlanId(Integer id) {
        Plan plan = new Plan();
        plan.setId(id);
        plan.setRef(REF);
        return planMapper.updateByPrimaryKeySelective(plan);
    }

    /**
     * 上传培训计划
     * @param planFront
     * @return
     */
    @Override
    public Integer insertPlan(PlanFront planFront) throws IOException {
        MultipartFile multipartFile = planFront.getMultipartFile();
        if(multipartFile==null){
            throw new BusinessRuntimeException(ResultCodeEnum.PLAN_UPLOAD.getCode(),ResultCodeEnum.PLAN_UPLOAD.getMessage());
        }
        String planUrl = FileTool.upLoad(multipartFile, ReadPropertiesUtil.readUrl("plan_url"));
        Plan plan = new Plan();
        plan.setPlanName(planFront.getPlanName());
        plan.setPlanYear(planFront.getPlanYear());
        plan.setFilePath(planUrl);
        plan.setUpdateTime(new Date());
        return planMapper.insertSelective(plan);
    }

    /**
     * 下载培训计划
     * @param id
     * @return
     */
    @Override
    public ResponseResult downloadPlan(Integer id) throws Exception {

        Plan plan = planMapper.selectByPrimaryKey(id);
        if (plan.getFilePath().isEmpty()){
            return ResponseResult.failure(ResultCodeEnum.FILE_FAILE_DownLoad.getCode(),ResultCodeEnum.FILE_FAILE_DownLoad.getMessage());
        }
        return ResponseResult.ok(plan.getFilePath());
    }


}
